<?php

require_once __DIR__.'/bootstrap.php';
require_once __DIR__.'/lib/silex.phar';

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;


$app = new Silex\Application();
$app['mongo'] = $app->share(function() {
	return new Istat\MongoIstat('prod', 'eureka'); 
});

$app->get('/', function() { return 'hello eureka<br/>use /places?city=Torino&year=2008 or /geo/lat/lon/(year)?radius=100'; } );

$app->get('/places/', function(Request $request) use ($app) {

  $year = (string) $request->get('year', false);
  $city = (string) $request->get('city', false);
  $type = (int) $request->get('type', false);

  $params = array();
  
  if ($year) $params['anno'] = $year;
  if ($city) $params['citta'] = $city;
  if ($type) $params['type'] = $type; //array('$exists' => true);
  
  $results = $app['mongo']->getPlaces($params);

  return json_encode($results);

});

$app->get('/geo', function() use ($app) {
  return "please add /latitude/longitude(/year) to the url";
});

$app->get('/geo/{lat}/{lon}', function($lat, $lon) use ($app) {

  $center = array( (float)$app->escape($lat), (float)$app->escape($lon) );
  $radius = $app['mongo']->km2radius($r = $app['request']->get('radius', 10));

  $results = $app['mongo']->getPlaceByGeo($center, $radius);

  return json_encode($results);

});

$app->get('/geo/{lat}/{lon}/{year}', function($lat, $lon, $year) use ($app) {

  $center = array( (float)$app->escape($lat), (float)$app->escape($lon) );

  $year = $app['request']->get('year', 2009);
  $type = (int) $request->get('type', false);

  $radius = $app['mongo']->km2radius($r = $app['request']->get('radius', 10));
  
  $results = $app['mongo']->getPlaceByYear($center, $year, $radius, $type);

  return json_encode($results);
});


$app['debug'] = true;
$app->run();
?>
